package com.aimaterials.resource.util;

import com.aimaterials.common.config.AiMaterialsConfig;
import com.aimaterials.common.constant.Constants;
import com.aimaterials.resource.domain.ResResource;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class FFmpegUtil {


    public static Map<String,String> handle(ResResource resResource) throws FFmpegCommandException {
        Map<String,String> map=new HashMap<String,String>();
        //存储在数据库的路径 /upload/2020/11/26/38ab0c2b-8200-4a95-a8b8-f7fd602e7ddb.mp4
        String filePath=resResource.getResourceUrl();
        //ffmpeg安装路径
        String ffmpegExePath= AiMaterialsConfig.getFfmpeg();
        //文件存在的绝对路径
        filePath=filePath.substring(Constants.RESOURCE_PREFIX.length());
        String fileAbs=AiMaterialsConfig.getProfile()+filePath;
        File tempfile=new File(fileAbs);
        if(!tempfile.exists()){
            return map;
        }
        //视频文件所在的目录绝对路径
        String finalPath=tempfile.getParentFile().getAbsolutePath();

//        //文件全名
        String fileALLName=filePath.substring(filePath.lastIndexOf("/")+1);
//        //文件名(不带后缀)
        String fileName=fileALLName.substring(0,fileALLName.lastIndexOf("."));

        String outputFilePath =finalPath+ File.separator+fileName+File.separator;

        File file=new File(outputFilePath);
        if(!file.exists()||!file.isDirectory()){
            file.mkdirs();
        }

        FFmpegCommandBuilder builder = new FFmpegCommandBuilder(ffmpegExePath);
        builder.input(fileAbs).forceCode("libx264").strict("2")
                .output(outputFilePath+fileName+".mp4");
        FFmpegCommand command = builder.build();
        try {
            String result = command.start(null);
            System.out.println(result);


        } catch (FFmpegCommandException e) {
            e.printStackTrace();
        }
        System.out.println("视频转码程序执行完毕，开始执行视频切片");

        FFmpegCommandBuilder builderCut = new FFmpegCommandBuilder(ffmpegExePath);
        builderCut.input(outputFilePath+fileName+".mp4").cutVideo().segmentList(fileName,outputFilePath);
        FFmpegCommand commandCut = builderCut.build();
        try {
            String result = commandCut.start(null);
            System.out.println(result);
        } catch (FFmpegCommandException e) {
            e.printStackTrace();
        }

        System.out.println("视频切片完毕，开始执行图片截取");

        FFmpegCommandBuilder builderPic = new FFmpegCommandBuilder(ffmpegExePath);
        builderPic.input(outputFilePath+fileName+".mp4").cutPic(fileName,outputFilePath);
        FFmpegCommand commandPic = builderPic.build();
        try {
            String result = commandPic.start(null);
            System.out.println(result);
        } catch (FFmpegCommandException e) {
            e.printStackTrace();
        }
        map.put("outputFilePath",outputFilePath);
        map.put("fileName",fileName);
        return map;
    }
}
